package com.sugon.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sugon.dto.Info;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: jichenglu
 * @create: 2019-12-18 10:02
 **/
@Service
public class IdentityCardService {

    @Value("classpath:region.json")
    private Resource resource;

    public List<Map> listMap;

    public String splitIdentityCard(String id){
        Pattern pattern = Pattern.compile("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
        if ("".equals(id) || id == null) {
            throw new IllegalArgumentException("身份证号不能为空");
        }
        Matcher matcher = pattern.matcher(id);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("身份证号码不合法");
        }

        Info info = new Info();

        //获取出生日期
        String birthdayStr = id.substring(6, 14);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = sdf1.parse(birthdayStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //获取出生日期
        String birthday = sdf2.format(date);

        //获取年龄
        String age = String.valueOf(ChronoUnit.YEARS.between(LocalDate.parse(birthday),LocalDate.now()));

        //获取性别
        String sex = "";
        if(Integer.parseInt(id.substring(16).substring(0, 1)) % 2 == 0){
            sex = "女";
        }else {
            sex = "男";
        }

        //获取省市区籍贯
        File file = null;
        try {
            file = resource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String dataJson = jsonRead(file);
        JSONObject jsonObject = JSON.parseObject(dataJson);
        JSONArray records = jsonObject.getJSONArray("RECORDS");
        listMap = records.toJavaList(Map.class);

//        String provinceCode = id.substring(0,2) + "0000";
//        String cityCode = id.substring(0,4) + "00";
//        String areaCode = id.substring(0,6);

        String code = id.substring(0,6);

        //获取省
        String province = "";
        //获取市
        String city = "";
        //获取县区
        String country = "";
        //获取籍贯
        String nativePlace = "";

//        for(Map<String,String> map : listMap){
//            if((map.get("code")).equals(provinceCode)){
//                province = map.get("name");
//                break;
//            }
//        }
//
//        for(Map<String,String> map : listMap){
//            if((map.get("code")).equals(cityCode)){
//                city = map.get("name");
//                break;
//            }
//        }
//
//        for(Map<String,String> map : listMap){
//            if((map.get("code")).equals(areaCode)){
//                area = map.get("name");
//                break;
//            }
//        }
//        String sql = "select mname from data_map_street where pcode = ? limit 1";
//        Map<String,Object> dataMap = jdbcTemplate.queryForMap(sql,code);
//        String mname = dataMap.get("mname").toString();
//        String[] strs = mname.split(",");

        for(Map<String,String> map : listMap){
            if((map.get("code")).equals(code)){
                nativePlace = map.get("name");
                break;
            }
        }

        String regex="(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<country>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        Matcher m=Pattern.compile(regex).matcher(nativePlace);
        while(m.find()){
            province = m.group("province");
            city = m.group("city");
            country = m.group("country");
        }


        info.setBirthday(birthday);
        info.setAge(age);
        info.setSex(sex);
        info.setProvince(province);
        info.setCity(city);
        info.setCountry(country);
        info.setNativePlace(nativePlace);

        return JSON.toJSONString(info);
    }

    /**
     * 将15位转换为18位
     * @param id 15位身份证号
     * @return String 18位身份证号
     */
    public String toEighteen(String id) {

        Pattern pattern = Pattern.compile("^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$");
        Matcher matcher = pattern.matcher(id);
        if (!matcher.matches()) {
            return id;
        }

        id = id.substring(0, 6) + "19" + id.substring(6);//加入年份，变成17位

        //计算校验位   begin
        char[] Ai = id.toCharArray();
        int[] Wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] verifyCode = {'1','0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int S = 0;
        int Y;
        for(int i = 0; i < Wi.length; i++){
            S += (Ai[i] - '0') * Wi[i];
        }
        Y = S % 11;
        //校验位计算结果verifyCode[Y] end

        id += verifyCode[Y];
        return id;
    }

    public String jsonRead(File file){
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {

        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return buffer.toString();
    }
}
